package com.woniu.service.impl;

import com.woniu.entity.ProductShipment;
import com.woniu.mapper.OrderMapper;
import com.woniu.mapper.ProductShipmentMapper;
import com.woniu.service.ProductShipmentService;
import com.woniu.util.ResponseEnum;
import com.woniu.util.ResponseUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
@Service
public class ProductShipmentServiceImpl implements ProductShipmentService {
    @Resource
    private ProductShipmentMapper mapper;
    @Resource
    private OrderMapper orderMapper;

    @Override
    public ResponseUtil findAll() {
        List<ProductShipment> list = mapper.findAll();
        return !list.isEmpty() ? ResponseUtil.get(ResponseEnum.OK, list)
                : ResponseUtil.get(ResponseEnum.FAIL);
    }
    @Override
    public ResponseUtil findByShipmentId(String shipmentId) {
        ProductShipment obj = mapper.findByShipmentId(shipmentId);
        return obj != null ? ResponseUtil.get(ResponseEnum.OK, obj)
                : ResponseUtil.get(ResponseEnum.FAIL);
    }
    @Override
    public ResponseUtil add(ProductShipment productShipment) {
        return mapper.add(productShipment) > 0
                ? ResponseUtil.get(ResponseEnum.OK)
                : ResponseUtil.get(ResponseEnum.FAIL);
    }
    @Override
    public ResponseUtil delete(String shipmentId) {
        return mapper.delete(shipmentId) > 0
                ? ResponseUtil.get(ResponseEnum.OK)
                : ResponseUtil.get(ResponseEnum.FAIL);
    }
    @Override
    public ResponseUtil update(ProductShipment productShipment) {
        // 若状态改为“已发货”（1），且发货时间为空，则自动填充当前时间
        if (productShipment.getStatus() != null && productShipment.getStatus() == 1
                && productShipment.getShipmentTime() == null) {
            productShipment.setShipmentTime(new Date());  // 后端确保时间正确
        }
        mapper.update(productShipment);
        ProductShipment shipment = mapper.findByShipmentId(productShipment.getShipmentId());
        String orderId = shipment.getOrderId();
        int i1 = orderMapper.updateOrderStatus(orderId, 3);
        return  i1> 0
                ? ResponseUtil.get(ResponseEnum.OK)
                : ResponseUtil.get(ResponseEnum.FAIL);
    }

    // 新增：条件查询实现
    @Override
    public ResponseUtil findByCondition(ProductShipment shipment) {
        List<ProductShipment> list = mapper.findByCondition(shipment);
        return !list.isEmpty() ? ResponseUtil.get(ResponseEnum.OK, list)
                : ResponseUtil.get(ResponseEnum.FAIL);
    }
}
